import 'package:cloudapp/exceptions/exceptions.dart';
import 'package:cloudapp/pages/user_login_page.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

import 'def.dart';

Future<bool> showToast(String body) {
  return Fluttertoast.showToast(msg: body);
}

Future<T> withException<T>(BuildContext context, FutureFunc<T> cb) async {
  try {
    return await cb();
  } on JsonDecodeError catch (e, stack) {
    await showToast("服务器响应数据错误");
    print('error: ${e.toString()}, stack: ${stack.toString()}');
  } on RequestException catch (e) {
    print('ERROR: ${e.code}, ${e.httpCode}, ${e.msg}');
    if(e.httpCode == 401) {
      print('token authorization failed, to user login.');
      Navigator.pushNamedAndRemoveUntil(context, UserLoginPage.pageName, (_) => false);
      return null;
    }
    await showToast(e.msg);
  } on Exception catch (e, stack) {
    await showToast("出错: ${e.toString()}");
    print('error: ${e.toString()}, stack: ${stack.toString()}');
  } catch (e, stack) {
    await showToast("未知错误: ${e.toString()}");
    print('error: ${e.toString()}, stack: ${stack.toString()}');
  }

  return null;
}
